// 1. React核心库
import React, { useState } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Card,
  Row,
  Col,
  Button,
  Form,
  Input,
  Checkbox,
  message,
  Typography,
  Space,
  Divider,
} from 'antd';

// 3. 图标库
import {
  UserOutlined,
  LockOutlined,
  LoginOutlined,
  UserAddOutlined,
} from '@ant-design/icons';

// 5. 工具库
import { history, useModel } from '@umijs/max';

// 6. 项目内部模块
import { apiClients, tokenManager } from '@/services/apiClient';

// 7. 类型定义
import type { InitialStateType } from '@/app';

// 解构常用子组件
const { Title, Text, Link } = Typography;

interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loginLoading, setLoginLoading] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');

  // 登录请求
  const handleLogin = async (values: LoginForm) => {
    try {
      setLoginLoading(true);
      const response = await apiClients.auth.authTokenCreate({
        tokenObtainPairRequest: {
          username: values.username,
          password: values.password,
        }
      });

      console.log('🚀 登录API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const tokenData = (response as any).data || response;

      if (tokenData && tokenData.access) {
        // 保存token
        tokenManager.setToken(tokenData.access);
        tokenManager.setRefreshToken(tokenData.refresh || '');

        // 获取用户信息 - 使用正确的API方法名
        const userResponse = await apiClients.auth.authMeRetrieve();
        // 🔑 关键：手动提取data字段
        const userData = (userResponse as any).data || userResponse;

        // 获取用户权限和组信息
        let userPermissions: string[] = [];
        let userGroups: string[] = [];

        try {
          const permissionResponse = await apiClients.permissions.permissionsUserGroupAssignmentsUserPermissionsRetrieve();
          console.log('🔐 权限API响应:', permissionResponse);

          // 🔑 关键：正确提取权限数据
          const permissionData = (permissionResponse as any).data || permissionResponse;

          if (permissionData && typeof permissionData === 'object') {
            userPermissions = permissionData.permissions || [];
            userGroups = permissionData.groups || [];
            console.log('✅ 权限解析成功:', { userPermissions, userGroups });
          }
        } catch (error) {
          console.warn('⚠️ 获取用户权限信息失败:', error);
          // 如果权限获取失败，但用户是超级用户，仍然可以继续
          if (userData?.is_superuser) {
            console.log('🎉 超级用户无需权限检查');
          }
        }

        // 更新全局状态
        setInitialState({
          name: initialState?.name || '用户管理系统',
          currentUser: userData,
          userPermissions,
          userGroups,
        });

        message.success('登录成功');

        // 跳转到首页
        const redirect = new URLSearchParams(window.location.search).get('redirect');
        history.push(redirect || '/home');

        return tokenData;
      } else {
        throw new Error('登录失败：未获取到有效token');
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '登录失败';
      message.error(errorMessage);
      throw error;
    } finally {
      setLoginLoading(false);
    }
  };

  const onFinish = (values: LoginForm) => {
    handleLogin(values);
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Card
        style={{
          width: '100%',
          maxWidth: 400,
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          borderRadius: '12px',
        }}
        styles={{ body: { padding: '40px' } }}
      >
        <div style={{ textAlign: 'center', marginBottom: '32px' }}>
          <div style={{
            width: '64px',
            height: '64px',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 16px',
          }}>
            <UserOutlined style={{ fontSize: '32px', color: 'white' }} />
          </div>
          <Title level={2} style={{ margin: 0, color: '#1f2937' }}>
            用户管理系统
          </Title>
          <Text type="secondary">请登录您的账户</Text>
        </div>

        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item>
            <Row justify="space-between" align="middle">
              <Col>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>记住我</Checkbox>
                </Form.Item>
              </Col>
              <Col>
                <Link href="#" style={{ color: '#667eea' }}>
                  忘记密码？
                </Link>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item style={{ marginBottom: '16px' }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loginLoading}
              block
              size="large"
              icon={<LoginOutlined />}
              style={{
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                height: '48px',
                borderRadius: '8px',
              }}
            >
              登录
            </Button>
          </Form.Item>

          <Divider plain>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              或者
            </Text>
          </Divider>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              block
              size="large"
              icon={<UserAddOutlined />}
              onClick={() => history.push('/register')}
              style={{
                height: '48px',
                borderRadius: '8px',
                borderColor: '#667eea',
                color: '#667eea',
              }}
            >
              注册新账户
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: 'center', marginTop: '24px' }}>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            © 2024 用户管理系统. All rights reserved.
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default Login;
